(function () {
 	var len=0;
 	var _dealLimit = 0.5; 
    //type
    jQuery('.typeBtn').on('click',function(){
    		if($(this).hasClass('active')){
    			$('.typeBtn').removeClass('active');
    			serverData.type = '';
    		}else{
    			$('.typeBtn').removeClass('active');
    			$(this).addClass('active');
    			serverData.type = $(this).val();
    		}
        serverTable.draw();
    });
    //查询
    jQuery('.app-btn-search').on('click',function(){
    	serverData.key=jQuery("#search").val();
    	serverTable.draw();
    });
    //撤销查询
    jQuery('.app-btn-cancel').on('click',function(){
        jQuery('#search').val('');
        serverData.key='';
        serverTable.draw();
    });
    
    ///认证通过
    jQuery('.accessBtn').on('click', function () {
    	if (jQuery("#checkEditForm") && !jQuery("#checkEditForm").Validform({
			tiptype : 3,
			showAllError : true
		}).check(false)) {
			return;
		};
		    var id = jQuery('#id').val();
	        var url = window.rootPath + "/ui/BusinesssellerAuthentication/accessCheck";
	        var d;
	        if(id!=''){
	        	  d = {
	        			"id": id,
	     	            "memo": jQuery('#memo').val()
	     	        };
	        jQuery.ajax({
	            type: 'post',
	            url: encodeURI(url),
	            data: JSON.stringify(d),
	            dataType: 'json',
	            contentType: 'application/json;charset=utf-8',
	            success: function (data) {
	            	if(data.code==-1){
	            		message("认证失败！");
	            	}
	            	else{
	            		message("认证通过！")
	            	}
	            	jQuery('#checkModal').modal('hide');
	                serverTable.draw(false);
	            }
	        });
	        }
    });
    
  ///认证拒绝
    jQuery('.rejectBtn').on('click', function () {
    	if (jQuery("#checkEditForm") && !jQuery("#checkEditForm").Validform({
			tiptype : 3,
			showAllError : true
		}).check(false)) {
			return;
		};
		    var id = jQuery('#id').val();
	        var url = window.rootPath + "/ui/BusinesssellerAuthentication/rejectCheck";
	        var d;
	        if(id!=''){
	        	  d = {
	        			"id": id,
	     	            "memo": jQuery('#memo').val()
	     	        };
	        jQuery.ajax({
	            type: 'post',
	            url: encodeURI(url),
	            data: JSON.stringify(d),
	            dataType: 'json',
	            contentType: 'application/json;charset=utf-8',
	            success: function (data) {
	            	if(data.code==-1){
	            		message("拒绝失败！");
	            	}
	            	else{
	            		message("拒绝通过！")
	            	}
	            	jQuery('#checkModal').modal('hide');
	                serverTable.draw(false);
	            }
	        });
	        }
    });
$(".addBtn").on('click',function(){
	window.location = window.rootPath
	+ '/ui/eventRegister?eventReportIdentify='+$("#eventReportIdentify").val();
});
    var serverData = {};
    serverData.type = "";
    var serverTable;
    jQuery(document).ready(function () {
    		_dealLimit = jQuery('#dealLimit').val();
        serverTable = jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/eventRegister/getpage?eventReportIdentify='+$("#eventReportIdentify").val(),
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
                {
                data: null
                },
                {
                    data: null,
                    defaultContent: "",
                    render: function (data, type, full, meta) {
                    	
                    	var operate ='<button type="button" class="btn btn-sm btn-info detailBtn" title="详情"><i class="fa fa-edit"></i></button>';
                    	if(data.registerEventState){
                    		if(data.registerEventState=='初始化'){
                        		operate+='<button type="button" class="btn btn-sm btn-info submitBtn" title="发布"><i class="fa fa-bullhorn"></i></button>';
                        	}else if(data.registerEventState=='已分配'){
                        		operate+='<button type="button" class="btn btn-sm btn-info backBtn" title="收回"><i class="fa fa-reply-all"></i></button>';
                        	}else if(data.registerEventState=='已退回'){
                        		operate+='<button type="button" class="btn btn-sm btn-info rejectBackBtn" title="确认退回"><i class="fa fa-recycle"></i></button>';
                        	}
                    	}
                    	
                        return operate;
                    }
                },
                {
                	data: 'registerEventName',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'registerEventContent',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'registerEventReportTime',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD HH:mm');
                        else
                            return '';
                    }
                },
                {
                    data: 'registerEventIdentify',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'registerEventType',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'registerEventEvaluateLevel',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'registerEventSeriousLevel',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },{
					data : "registerEventImgAdress",
					render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return '<img width="50%" src="'+window.rootPath+"/"+data+'" />';
						}
					}

				},
                {
                    data: 'registerEventAdress',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'registerEventToNetGrid',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'registerEventState',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                }
              ],
            "createdRow":function(row, data, dataIndex){
            	//$(row).css("background", "#588600");  
            	//获取事件状态
            	var state=data.registerEventState;
            	
            	//事件的处理时限
            	var dealLimit=3600 * data.dealLimitSpan;
            	//系统当前时间
            	var d=new Date().getTime();//ms
            	
            	//$("#underTimeOutRegisterLi").show();
            	if(state=="处理中"){
            		//事件接收时间
            		//var t=new Date(data.eventTask.eventTaskTime).getTime();
//            		var t=new Date(data.outTask.eventTaskTime).getTime();
//            		
//            		var delay=(d-t)/1000;
//            		
//            		var undelay=dealLimit*2/3;
//            		
//            		//即将超时
//            		if(delay<dealLimit&&delay>undelay){
//            		
//            			sendMessage(row, data, dataIndex);
//            			
//            		}
//            		//已经超时
//            		if(delay>dealLimit){
//            			$(row).css("background", "red"); 
//            			
//            		}
            		
            		var diffTime = data.diffTime;
            		var dealLimitSpan = data.dealLimitSpan;
            		var d = dealLimitSpan - diffTime;
            		//即将超时
            		if(d >= 0 && d <= _dealLimit){
            			sendMessage(row, data, dataIndex);
            		}
            		//已经超时
            		if(d < 0){
            			$(row).css("background", "red"); 
            			
            		}
            	}
            },
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }
              
                serverTable.off('click', 'tr');
                serverTable.on('click', 'tr', function (event) {
                    event = event || window.event;
                    var target = event.target || event.scrElement;
                    var data = serverTable.row(this).data();
                    if (target.className.indexOf('fa-bullhorn') != -1 ||target.className.indexOf('submitBtn') != -1) {
                    	submitBtnQ(data);
                    }
                    if (target.className.indexOf('fa-reply-all') != -1 ||target.className.indexOf('backBtn') != -1) {
                    	backBtnQ(data);
                    }
                    
                    if (target.className.indexOf('fa-edit') != -1 ||target.className.indexOf('detailBtn') != -1) {
                        showDetail(data);
                    }
                    if (target.className.indexOf('fa-recycle') != -1 ||target.className.indexOf('rejectBackBtn') != -1) {
                    	rejectBackBtnQ(data);
                    }
                    
                    if($(this).hasClass('selected') ){
	            			$(this).removeClass('selected');
	            			getProcedure('');
	            		}else{
	            			serverTable.$('tr.selected').removeClass('selected');
	            	    		$(this).addClass('selected');
	            	    		getProcedure(data.id);
	            	    }
                    return;
                });
            }
        });
        var rejectBackBtnQ=function(o){
        	 $("#rejectBackId").val(o.id);
        	 
        	jQuery('#rejectBackModal').modal('show');
			$.ajax({
				url : rootPath + "/ui/eventRegister/getRejectBackReason?id="
						+ $("#rejectBackId").val(),
				dataType : 'json',
				type : 'get',
				contentType : "application/json",
				success : function(result) {
					if (result.data.code <= 0) {
						message("获取退回原因失败!");
					} else {
						if(result.data.reasonStr){
							$("#rejectBackReason").val(result.data.reasonStr.eventTaskMemo);
							if(result.data.reasonStr.eventTaskUser){
								$("#rejectBackPerson").val(result.data.reasonStr.eventTaskUser.name);
							}
						}
					}
				}
			});
        }
        $(".saverejectBackBtn").on(
        		'click',
        		function() {
        			var data = {
        				"id" : $("#rejectBackId").val(),
        				"rejectBackMemo" : $("#rejectBackMemo").val(),
        			}
        			$.ajax({
        				url : rootPath + "/ui/eventRegister/rejectBackEventRegister",
        				dataType : 'json',
        				data : JSON.stringify(data),
        				type : 'post',
        				contentType : "application/json",
        				success : function(result) {
        					if (result.data.code <= 0) {
        						message("操作失败!");
        					} else {
        						message(result.data.rejectBackStr);
        					}
        					jQuery('#rejectBackModal').modal('hide');
        					serverTable.draw(false);
        				}
        			});
        		});
        var backBtnQ=function(o){
        	jQuery('#backModal').modal('show');
        	$("#backId").val(o.id);
        };
        $(".savebackBtn").on(
        		'click',
        		function() {
        			var data = {
        				"id" : $("#backId").val(),
        				"backMemo" : $("#backMemo").val(),
        			}
        			$.ajax({
        				url : rootPath + "/ui/eventRegister/backEventRegister",
        				dataType : 'json',
        				data : JSON.stringify(data),
        				type : 'post',
        				contentType : "application/json",
        				success : function(result) {
        					if (result.data.code <= 0) {
        						message("操作失败!");
        					} else {
        						message(result.data.backStr);
        					}
        					jQuery('#backModal').modal('hide');
        					serverTable.draw(false);
        				}
        			});
        		});
        var submitBtnQ=function(o){
        	var data = {
    				"id" : o.id
    			}
    			$.ajax({
    				url : rootPath + "/ui/eventRegister/submitEventRegister",
    				dataType : 'json',
    				data : JSON.stringify(data),
    				type : 'post',
    				contentType : "application/json",
    				success : function(result) {
    					if (result.data.code <= 0) {
    						message("操作失败!");
    					} else {
    						message(result.data.submitStr);
    					}
    					serverTable.draw(false);
    				}
    			});
        }
        var showDetail=function(o){
	        	if(!o) return;
	        	window.location = window.rootPath
	        	+ '/ui/eventRegister?eventReportIdentify='+o.registerEventToReportEvent+"&eventRegisterIdentify="+o.id;
        }
    });
    function sendMessage(row, data, dataIndex){
	    	$("#underTimeOutRegisterLi").show();
	    	$(row).css("background", "yellow"); 
    };
    
    //获取流转详情
    function getProcedure(id) {
	    	$("#procedureB").empty();
	    	if(id == '') return;
	    	$.ajax({
	    		url : rootPath + '/ui/eventRegister/getProcedure/' + id,
	    		dataType : 'json',
	    		type : 'get',
	    		success : function(result) {
	    			if (result.code == 1) {
	    				var list = result.data.procedures;
	    				$.each(list, function() {
	    					var tr = $("<tr></tr>");
	    					var opTd = $("<td>" + this.eventTaskOperate + "</td>");
	    					var stateTd = $("<td>" + this.eventTaskState.title
	    							+ "</td>");
	    					var timeTd = $("<td>"
	    							+ moment(this.eventTaskTime).format(
	    									"YYYY/MM/DD HH:mm") + "</td>");
	    					var userTd = $("<td>" + this.eventTaskUser.name + "</td>");
	    					$("#procedureB").append(tr).append(opTd).append(stateTd)
	    							.append(timeTd).append(userTd);
	    				});
	    			}
	    		}
	    	})
	    	// $("#detailsShow").show();
    };
    
})();